package com.zxsc.zxmusic.fragment;

import java.util.ArrayList;
import java.util.List;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import butterknife.ButterKnife;
import com.zxsc.zxmusic.MainActivity;
import com.zxsc.zxmusic.R;
import com.zxsc.zxmusic.UserActivity;
import com.zxsc.zxmusic.adapter.AdapterAlbum;
import com.zxsc.zxmusic.adapter.AdapterAlbum.OnLongClickLister;
import com.zxsc.zxmusic.db.SongDb;
import com.zxsc.zxmusic.manager.SongManager;
import com.zxsc.zxmusic.model.SongInfo;
import com.zxsc.zxmusic.model.SongMenuModel;
import com.zxsc.zxmusic.service.PlayService;
import com.zxsc.zxmusic.utils.ToastUtils;
import com.zxsc.zxmusic.utils.UserUtils;

public class AlbumFragment extends BaseFragment implements
		PlayService.IMusicListener, OnClickListener, OnGroupClickListener,
		OnChildClickListener, OnLongClickLister {

	private List<SongMenuModel> menus;
	private List<List<SongMenuModel>> songs;
	private AdapterAlbum adapterAlbum;
	private PlayService mPlayService;

	ExpandableListView listView;

	private ServiceConnection playConn = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			PlayService.MyBinder binder = (PlayService.MyBinder) service;
			mPlayService = binder.getService();
			mPlayService.addMusicListener(AlbumFragment.this);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
		}
	};

	@Override
	protected View inflateView(LayoutInflater inflater, ViewGroup container) {

		Intent playIntent = new Intent(getActivity(), PlayService.class);
		getActivity().startService(playIntent);
		getActivity().bindService(playIntent, playConn,
				Context.BIND_AUTO_CREATE);

		View view = inflater.inflate(R.layout.fragment_album, container, false);
		ButterKnife.bind(this, view);
		initView(view);
		return view;
	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

	}

	private void initView(View view) {
		menus = new ArrayList<SongMenuModel>();
		songs = new ArrayList<List<SongMenuModel>>();
		listView = (ExpandableListView) view.findViewById(R.id.album_list);
		listView.setOnGroupClickListener(this);
		listView.setOnChildClickListener(this);
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (view.getId() == -1) {
					showDialogs(menus.get(position));
				} 

				return false;
			}
		});

		((MainActivity) getActivity()).setCreateMenuLister(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		ButterKnife.unbind(this);
		// LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
	}

	@Override
	protected void onLoading() {
		SongManager.with(getActivity()).fetchSongFromDb();

	}

	@Override
	protected void onLoadFinish() {

		if (UserUtils.getInstance().getUserName() != null
				&& UserUtils.getInstance().getUserName().length() > 0) {
			getDataList();
		}

	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);

	}

	private void getDataList() {
		List<SongMenuModel> list = SongDb.getAllSongMenu(getActivity(),
				UserUtils.getInstance().getUserId());
		menus.clear();
		songs.clear();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				menus.add(list.get(i));
				List<SongMenuModel> model = SongDb.findAllSongs(getActivity(),
						list.get(i));
				if (model != null && model.size() > 0) {
					songs.add(model);
				}
			}
		}

		upDataList();

	}

	private void upDataList() {
		if (adapterAlbum == null) {
			adapterAlbum = new AdapterAlbum(getActivity(), menus, songs);
			adapterAlbum.setOnLongClickLister(this);
			listView.setAdapter(adapterAlbum);
		}
		adapterAlbum.notifyDataSetChanged();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.title_right://
			createMenus();
			break;
		}
	}

	private void createMenus() {
		if (UserUtils.getInstance().getUserName() != null
				&& UserUtils.getInstance().getUserName().length() > 0) {
			showDialog(getActivity(),1,1,null);
		} else {
			startActivityForResult(
					new Intent(getActivity(), UserActivity.class), 100);
		}
	}

	private void showDialog(Context context,final int type,int position,final SongMenuModel menuModel) {
		final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
		View view = LayoutInflater.from(context).inflate(
				R.layout.dialog_create_menu, null);
		final EditText etMenuName = (EditText) view
				.findViewById(R.id.dialog_menu_name);
		final Button btnOk = (Button) view.findViewById(R.id.dialog_menu_btnok);
		final Button btnCancle = (Button) view
				.findViewById(R.id.dialog_menu_btncancle);
		dialog.setView(view);
		final Dialog dialogs = dialog.show();
		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String name = etMenuName.getText().toString().trim();
				if(type==0){//编辑歌单
					editMenu(name,dialogs, menuModel);
				}else{//创建歌单
					createMenu(name,dialogs);
				}
			}
		});
		btnCancle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialogs.dismiss();
			}
		});

	}
	
	/**
	 * 创建歌单
	 * @param name
	 * @param dialogs
	 */
	private void createMenu(String name,Dialog dialogs){
		if (name != null && name.length() > 0) {
			SongMenuModel songMenuModel = new SongMenuModel(Base64
					.encodeToString(name.getBytes(), Base64.DEFAULT),
					UserUtils.getInstance().getUserId(), name, -1l);
			if (SongDb.isCreateMenu(getContext(),
					UserUtils.getInstance(), songMenuModel)) {
				if (SongDb.createMenu(getContext(), songMenuModel)) {
					ToastUtils.show(getActivity(), "创建成功");

					getDataList();
					dialogs.dismiss();
				} else {
					ToastUtils.show(getActivity(), "创建失败");
				}
			} else {
				ToastUtils.show(getActivity(), "列表已经存在");
			}
		} else {
			ToastUtils.show(getActivity(), "列表名称不能为空！");
		}
		
	}
	
	/**
	 * 编辑歌单
	 * @param name
	 * @param dialogs
	 * @param songMenuModel
	 */
	private void editMenu(String name,Dialog dialogs,SongMenuModel songMenuModel){
		if(SongDb.editSongMenu(getActivity(), songMenuModel,name)){
			ToastUtils.show(getActivity(), "编辑歌单成功");
			getDataList();
		}else{
			ToastUtils.show(getActivity(), "编辑歌单失败");
		}
		
		dialogs.dismiss();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 100) {
			if (data != null && data.getBooleanExtra("isLogin", false)) {
				getDataList();
				createMenus();
			}
		}
	}

	@Override
	public boolean onGroupClick(ExpandableListView parent, View v,
			int groupPosition, long id) {
		if (songs.size() < (groupPosition + 1)) {
			return true;// 不展开

		} else {

			return false;
		}
	}

	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {
		// if(!((songs.size()<=0?0:songs.size()-1)<(groupPosition))){
		SongMenuModel songMenu = songs.get(groupPosition).get(childPosition);
		SongInfo info = SongManager.with(getActivity()).getSongById(
				songMenu.getSongId());
		if (info != null) {
			mPlayService.play(info.getId());
		} else {
			ToastUtils.show(getActivity(), "播放失败，请重新登陆！");
		}
		// }
		return true;
	}

	@Override
	public void onMusicPlay(int songId) {
		if (getActivity() != null) {
			((MainActivity) getActivity()).onMusicPlay(songId);
		}// TODO Auto-generated method stub

	}

	@Override
	public void onMusicPlayByUser(int songId) {
		if (getActivity() != null) {
			((MainActivity) getActivity()).onMusicPlay(songId);
		}

	}

	@Override
	public void onMusicPause() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onMusicStop() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onMusicPlaying(int progress, long max) {
		// TODO Auto-generated method stub

	}

	/**
	 * 更新歌曲UI
	 * 
	 * @param lastSong
	 */
	@Subscriber(tag = "up")
	void OnUpData(String str) {
		getDataList();
	}

	@Override
	public void OnLongClick(int position, SongMenuModel menuModel) {
		ToastUtils.show(getActivity(), position + "");
	}

	private void showDialog(int type, String message,
			final SongMenuModel menuModel) {
		if(type==0) {// 编辑歌单
			showDialog(getActivity(),0,1,menuModel);
		}else if(type == 1) {// 歌单
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setTitle("删除歌单");
			builder.setMessage("删除歌单 " + message + " ?");
			builder.setNegativeButton("确定",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							
							if (SongDb.deleteSongMenu(getActivity(), menuModel)) {
								ToastUtils.show(getActivity(), "已删除  "
										+ menuModel.getMenuName());
								getDataList();
							} else {
								ToastUtils.show(getActivity(), "删除："
										+ menuModel.getMenuName() + "失败！");
							}

							dialog.dismiss();
						}
						
					});
			builder.show();
		} 
		
	}

	/**
	 * 编辑删除
	 * @param type
	 * @param menuModel
	 */
	@SuppressWarnings("unused")
	private void showDialogs(final SongMenuModel menuModel) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setItems(new String[] { "编辑选中歌单", "删除选中歌单" },
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-menuModel method stub
						switch (which) {
						case 0://编辑
							showDialog(0, menuModel.getMenuName(), menuModel);
							dialog.dismiss();
							break;
						case 1://删除
							showDialog(1, menuModel.getMenuName(), menuModel);
							dialog.dismiss();
							break;
						}
						
					}
				});

		builder.show();
	}
	

}
